function createTree (data, treeWrap, selectArr = []) {
  let treeWrapHtml = `<div id="typeContainer" class="tree-wrap"><div class="tree-type" id="typeWrap"></div><div class="tree-company" id="companyWrap"></div><div id="departmentWrap" class="tree-department"></div></div><input id="typeVal" type="hidden"><input id="companyVal" type="hidden"><input id="departmentVal" type="hidden">`
  const companyData = formatCompanyData(data.innerList, 'inner')
  const departmentData = formatDepartmentData(companyData[0].childrens)

  formatCompanyData(data.outerList.friendList, 'friend')
  formatCustomerData(data.outerList.customerList, 'customer')

  treeWrap.html(treeWrapHtml)
  createTypeHtml(data)
  createCompanyHtml(companyData)
  createDepartmentHtml([])
}

function createTypeHtml (allData) {
  const typeArr = [
    {
      id: 0,
      title: '内部',
      level: 0,
      parentId: -1,
      type: 'inner'
    },
    {
      id: 1,
      title: '外部',
      level: 0,
      parentId: -1,
      type: 'outter',
      children: [
        {
          id: 2,
          title: '好友公司',
          level: 1,
          parentId: 1,
          type: 'friend'
        },
        {
          id: 3,
          title: '客商',
          level: 1,
          parentId: 1,
          type: 'customer'
        },
        {
          id: 4,
          title: '供应商',
          level: 1,
          parentId: 1,
          type: 'supply'
        }
      ]
    },
  ]

  layui.use(['tree', 'util'], function () {
    var tree = layui.tree
      , layer = layui.layer
      , util = layui.util

    tree.render({
      elem: '#typeWrap'
      , data: typeArr
      , showCheckbox: true  //是否显示复选框
      , id: 'typeTree'
      , isJump: true //是否允许点击节点时弹出新窗口跳转
      , click: function (obj) {
        $(obj.elem).find('input').prop('checked')
        if (!obj.data.hasOwnProperty('children')) {
          switch (obj.data.type) {
            case 'inner':
              createCompanyHtml(allData.innerList)
              break;
            case 'friend':
              createCompanyHtml(allData.outerList.friendList)
              break;
            case 'customer':
              createCompanyHtml(Object.values(allData.outerList.customerList))
              break;
            case 'supply':
              createCompanyHtml(allData.outerList.supplyList)
              break;
          }
        }
        tree.setChecked('companyTree', typeArr)
        tree.reload('departmentTree', [])
      },
      oncheck: function (obj) {
        const checkedArr = $('#companyVal').val() ? $('#companyVal').val().split(',') : []
        let typeIdArr
        if (!obj.data.hasOwnProperty('children')) {
          switch (obj.data.type) {
            case 'inner':
              typeIdArr = getCheckedId(Object.values(allData.innerList))
              Object.keys(allData.innerList).forEach(item => {
                if (obj.checked) {
                  allData.innerList[item].checked = true
                } else {
                  allData.innerList[item].checked = false
                }
              })

              if (obj.checked) {
                tree.setChecked('companyTree', typeIdArr)
              } else {
                // $('#companyWrap').find('input').each(function () {
                //   if (typeArr.includes($(this).val())) {
                //     $(this).prop('checked', false)
                //     $(this).parent().find('.layui-form-checked').removeClass('layui-form-checked')
                //   }
                // })
                tree.reload('departmentTree', [])
              }
              break;
            case 'friend':
              typeIdArr = getCheckedId(Object.values(allData.outerList.friendList))
              Object.keys(allData.outerList.friendList).forEach(item => {
                if (obj.checked) {
                  allData.outerList.friendList[item].checked = true
                } else {
                  allData.outerList.friendList[item].checked = false
                }
              })

              if (obj.checked) {
                tree.setChecked('companyTree', typeIdArr)
              } else {
                $('#companyWrap').find('input').each(function () {
                  if (typeIdArr.includes($(this).val())) {
                    $(this).prop('checked', false)
                    $(this).parent().find('.layui-form-checked').removeClass('layui-form-checked')
                  }
                })
                tree.reload('departmentTree', [])
              }
              break;
            case 'customer':
              // console.log(Object.values(allData.outerList.customerList))
              typeIdArr = getCheckedId(Object.values(allData.outerList.customerList))

              createCompanyHtml(allData.outerList.customerList)
              Object.keys(allData.outerList.customerList).forEach(item => {
                if (obj.checked) {
                  allData.outerList.customerList[item].checked = true
                } else {
                  allData.outerList.customerList[item].checked = false
                }
              })

              if (obj.checked) {
                tree.setChecked('companyTree', typeIdArr)
              } else {
                $('#companyWrap').find('input').each(function () {
                  if (typeIdArr.includes($(this).val())) {
                    $(this).prop('checked', false)
                    $(this).parent().find('.layui-form-checked').removeClass('layui-form-checked')
                  }
                })
                tree.reload('departmentTree', [])
              }
              break;
            case 'supply':
              createCompanyHtml(allData.outerList.supplyList)
              break;
          }
        }

        if (obj.checked) {
          checkedArr.push(obj.data.id)
          tree.setChecked('companyTree', getCheckedId(obj.data.childrens ? obj.data.childrens : []))
        } else {
          tree.reload('companyTree', [])
          tree.reload('departmentTree', [])
          console.log(getCheckedId(tree.getChecked('typeTree')))

          if (checkedArr.includes(obj.data.id)) {
            const idx = checkedArr.indexOf(objId)

            checkedArr.splice(idx, 1)
          }
        }

        $('#companyVal').val(checkedArr ? [...new Set(checkedArr)].join(',') : '')
        obj.data.children && removeChildId(obj.data.children)
        switch (obj.data.type) {
          case 'inner':
            removeChildId(getCheckedId(allData.innerList))
            break;
          case 'friend':
            removeChildId(getCheckedId(allData.outerList.friendList))
            break;
          case 'customer':
            removeChildId(Object.values(allData.outerList.customerList))
            break;
          case 'supply':
            removeChildId(allData.outerList.supplyList)
            break;
        }
        createDepartmentHtml([])
      }
    });
  })
}

function createCompanyHtml (data) {
  layui.use(['tree', 'util'], function () {
    var tree = layui.tree
      , layer = layui.layer
      , util = layui.util

    tree.render({
      elem: '#companyWrap'
      , data: data
      , showCheckbox: true  //是否显示复选框
      , id: 'companyTree'
      , isJump: true //是否允许点击节点时弹出新窗口跳转
      , click: function (obj) {
        if (obj.data.hasOwnProperty('childrens') && obj.data.childrens.length > 0) {
          const arr = getCheckedId(tree.getChecked('companyTree'))
          const checked = arr.includes(obj.data.id)
          const departmentData = formatDepartmentData(obj.data.childrens, checked)
          const parentId = obj.data.pid

          createDepartmentHtml(departmentData)
        }

      },
      oncheck: function (obj) {
        const checkedArr = $('#companyVal').val() ? $('#companyVal').val().split(',') : []
        let id = null, objId = obj.data.id, newCheckedArr = []

        switch (obj.data.ftype) {
          case 'inner':
            id = 0
            break;
          case 'friend':
            id = 2
            break;
          case 'customer':
            id = 3
            break;
          case 'supply':
            id = 4
            break;
        }

        if (obj.checked) {
          let allChecked = true
          let childArr = getCheckedId(obj.data.childrens)

          tree.setChecked('departmentTree', childArr)

          $('#companyWrap').find('input').each(function () {
            if (!$(this).prop('checked')) {
              allChecked = false
            }
          })

          if (allChecked) {
            tree.setChecked('typeTree', [id])
            removeChildId(getCheckedId(tree.getChecked('companyTree')))
          }


          // let itemTree = $('#companyWrap').find('.layui-tree-setHide')

          // for (let i = 0; i < itemTree.length; i++) {
          //   let childItem = $(itemTree[i]).find('.layui-tree-pack .layui-tree-set input')
          //   for (let i = 0; i < childItem.length; i++) {
          //     if (!$(childItem[i]).prop('checked')) {
          //       $(childItem[i]).parents('.layui-tree-setHide').find('.layui-tree-entry').eq(0).find('.layui-unselect').removeClass('layui-form-checked')
          //       $(childItem[i]).parents('.layui-tree-setHide').find('.layui-tree-entry').eq(0).find('input').prop('checked', false)
          //       return
          //     } else {
          //       $(childItem[i]).parents('.layui-tree-setHide').find('.layui-tree-entry').eq(0).find('.layui-unselect').addClass('layui-form-checked')
          //       $(childItem[i]).parents('.layui-tree-setHide').find('.layui-tree-entry').eq(0).find('input').prop('checked', true)
          //       return
          //     }
          //   }
          // }


          if (obj.data.level == 0) {
            checkedArr.push(id)

          } else {
            checkedArr.push(objId)
          }
        } else {
          if (checkedArr.includes(objId)) {
            const idx = checkedArr.indexOf(objId)

            checkedArr.splice(idx, 1)
          }

          if (obj.data.level == 0) {
            const idx = checkedArr.indexOf(id)

            checkedArr.splice(idx, 1)

            const companyIdArr = getCheckedId(tree.getChecked('companyTree'))

            newCheckedArr = [...checkedArr, ...companyIdArr]
          }
          unchecked($('#departmentWrap'))
          $('#typeWrap').find('input').each(function () {
            if ($(this).val() == id) {
              $(this).prop('checked', false)
              $(this).parent().find('.layui-form-checked').removeClass('layui-form-checked')
            }
          })

        }

        let companyCheckedArr = []
        if (newCheckedArr && newCheckedArr.length > 0) {
          companyCheckedArr = newCheckedArr
        } else if (checkedArr && checkedArr.length > 0) {
          companyCheckedArr = checkedArr
        }
        companyCheckedArr = companyCheckedArr.join(',').split(',')
        $('#companyVal').val(companyCheckedArr ? [...new Set(companyCheckedArr)].join(',') : '')
        removeChildId(getCheckedId(obj.data.childrens))
      }
    });
  })
}

function removeChildId (idArr) {
  let checkedArr = $('#companyVal').val() ? $('#companyVal').val().split(',') : []

  idArr.map(id => {
    if (checkedArr.includes(id)) {
      const idx = checkedArr.indexOf(id)

      checkedArr.splice(idx, 1)
    }
  })

  $('#companyVal').val(checkedArr.join(','))
}

function createDepartmentHtml (data) {
  layui.use(['tree', 'util'], function () {
    var tree = layui.tree
      , layer = layui.layer
      , util = layui.util

    tree.render({
      elem: '#departmentWrap'
      , data: data
      , showCheckbox: true  //是否显示复选框
      , id: 'departmentTree'
      , isJump: true //是否允许点击节点时弹出新窗口跳转
      , click: function (obj) {
        var data = obj.data;  //获取当前点击的节点数据
        // layer.msg('状态：' + obj.state + '<br>节点数据：' + JSON.stringify(data));
      },
      oncheck: function (obj) {
        let allChecked = true
        let checkedArr = $('#companyVal').val() ? $('#companyVal').val().split(',') : [];

        $('#departmentWrap').find('input').each(function () {
          if (!$(this).prop('checked')) {
            allChecked = false
          }
        })

        if (obj.checked && !checkedArr.includes(obj.data.id)) {
          checkedArr.push(obj.data.id)
        } else if (!obj.checked && checkedArr.includes(obj.data.id)) {
          checkedArr = checkedArr.splice(checkedArr.indexOf(obj.data.id), 1)
        }
        $('#companyVal').val(checkedArr ? [...new Set(checkedArr)].join(',') : '')

        if (allChecked) {
          tree.setChecked('companyTree', [obj.data.pid])
        } else {
          $('#companyWrap').find('input').each(function () {
            if ($(this).val() == obj.data.pid) {
              $(this).prop('checked', false)
              $(this).parent().find('.layui-form-checked').removeClass('layui-form-checked')
            }
          })
        }
      }
    });
  })
}

function unchecked (dom) {
  $(dom).find('.layui-tree-main').each(function () {
    $(this).find('input').prop('checked', false)
    $(this).find('.layui-form-checked').removeClass('layui-form-checked')
  })
}

function selectAll (data, arr, status = true) {
  data.map(obj => {
    if (!arr.includes(obj.id)) {
      status = false
      return
    }
  })
  return status
}

function getCheckedId (list, arr = []) {
  if (!list || !list.length) {
    return []
  }
  list.map(obj => {
    arr.push(obj.id)
    if ((obj.hasOwnProperty('children') && obj.children.length > 0) || (obj.hasOwnProperty('childrens') && obj.childrens.length > 0)) {
      const data = obj.children.length > 0 ? obj.children : obj.childrens;
      getCheckedId(data, arr)
    }
  })
  return arr
}

function formatCompanyData (data, t, id = 0) {
  Object.keys(data).map(k => {
    data[k].ftype = t
    data[k].name ? data[k].title = data[k].name : ''
    data[k].pid = id
    if (data[k].hasOwnProperty('children') && Object.keys(data[k].children).length > 0) {
      formatCompanyData(data[k].children, t, data[k].id)

      data[k].childrens = Object.values(data[k].children)
      if (data[k].type === 'company' || data[k].type === 'customer') {
        let arr = []
        Object.values(data[k].children).map(obj => {
          if (obj.type === 'company' || obj.type === 'customer') {
            arr.push(obj)
          }
        })
        data[k].children = arr
      }
    }
  })
  return Object.values(data)
}

function formatDepartmentData (data, isChecked) {
  let arr = []
  data.map(obj => {
    if (obj.type !== 'company') {
      obj.checked = isChecked
      if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
        obj.children = obj.childrens
        formatDepartmentData(obj.childrens, isChecked)
      }
      arr.push(obj)
    }
  })
  return arr
}

function formatCustomerData (data, t) {
  let arr = []
  Object.values(data).map(obj => {
    obj.ftype = t
    obj.title = obj.name
    arr.push(obj)
  })
  return arr
}